package predictors;

import utils.Msg;
import utils.Utils;
import jobqueue.JobQueueInfo;
import jsonobj.JobInfo;
import jsonobj.Message;
import data.UserInfo;

public class SubmitJob implements Runnable {
	UserInfo ui;
	JobInfo ji;

	public SubmitJob(UserInfo u, JobInfo j) {
		this.ui = u;
		this.ji = j;
	}

	@Override
	public void run() {
		try {
			if(ui.getAllOnlineClusters().isEmpty())
			{
				ui.sendMessage(new Message(Msg.NO_ONLINE_CLU));
				//return;
			}
			if (ji.clu == null) {
				Utils.out("<IN PRED>");
				switch (ji.opt) {
				case 0: {
					AttrInfo i = AttributeMatcherImpl.GetLowestQtime(ji, ui);
					//Utils.out("JOB SUBMISSION: "+i.jobname+" "+i.low_bound+" "+i.cluster);
					if(ui.clusters.get(i.getCluster()).isConnected)
					{
						ui.clusters.get(i.getCluster()).sendMessage(ji);
						ui.sendMessage(i);
					}
					else
					{
						Utils.out("+ Cannot send request: cluster no connected");
					}
					
					break;
				}
				case 1: {
					ProbaInfo i = ResourcePredictorImpl
							.GetHighestProbability(ji);
					Utils.jobq.InsertJob(new JobQueueInfo(ji, i, ui));
					i.h_prob.jobname = ji.jname;
					Utils.out(i.h_prob.toString());
					ui.sendMessage(i.h_prob);
					break;
				}
				case 2: {
					Co2Info ci = CO2PredictorImpl
							.GetAvgLowestEmissionDateInTimeRange(ji.trange);
					ProbaInfo i = ResourcePredictorImpl.GetHighestProbability(
							ji, ci.date, 0);
					Utils.jobq.InsertJob(new JobQueueInfo(ji, i, ui));
					ci.setCluster(i.cluster);
					ji.clu = i .cluster;
					ci.jobname = ji.jname;
					ui.sendMessage(ci);
					break;
				}
				}
			} else {
				ui.clusters.get(ji.clu).sendMessage(ji);
			}
			ui.jobs.add(ji);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
